<template>
  <div>
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i>首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/sys-admin/product/album' }">相册列表</el-breadcrumb-item>
      <el-breadcrumb-item><span>{{ album.name }}</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 图片列表 -->
    <div class="picture-list">
      <!-- 上传组件 -->
      <div class="upload">
        <!-- 提示 -->
        <div class="tips">
          <p><b>提示:</b>只能上传<i>image/jpeg,image/png</i>类型的图片，单张图片不超过<i>20MB</i>，暂不支持多张上传！</p>
        </div>
        <div class="upload-main">
          <el-upload
              ref="upload"
              action="http://localhost:9182/resource/upload/image/product"
              :file-list="pictureList"
              :show-file-list="false"
              :auto-upload="false"
              :on-success="onSuccess"
              :on-change="handleChange">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器
            </el-button>
          </el-upload>
        </div>

        <!--即将上传的图片信息-->
        <div v-if="imageSrc" style="height:80px;width: 230px; border: 1px solid #e8e6e6;padding: 5px;float: left">
          <div class="picture-info" style="margin-top: 10px">图片信息：
            <p style="font-size: 13px;display: inline">{{ width }}px * {{ height }}px</p>
          </div>

          <el-button @click="cancelUpload" size="mini" style="margin-top: 14px">取消上传</el-button>
        </div>
      </div>
      <div class="picture-item" v-for="picture in pictureList">
        <!--设置封面图片-->
        <div class="cover-flag">
          <el-button class="cover-button" @click="openSetCoverConfirm(picture)"
                     :class="picture.isCover ==1 ? 'cover' : 'not-cover' " icon="el-icon-s-flag"></el-button>
        </div>
        <!-- 删除按钮 -->
        <div class="delete-button">
          <el-button class="button" @click="deleteImageConfirm(picture)" type="danger" size="mini"
                     icon="el-icon-delete-solid"></el-button>
        </div>
        <!-- 图片列表 -->
        <el-image class="image"
                  :key="picture.id"
                  :src="picture.url"
                  :preview-src-list="srcList"
                  fit="cover"></el-image>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 当前显示图片列表的相册数据
      album: {
        id: 0,
        name: '相册名称'
      },
      // 上传时显示的图片信息
      imageSrc: null,
      width: 0,
      height: 0,
      // 图片列表数据
      pictureList: [],
      // 图片url列表数据
      srcList: []
    };
  },
  methods: {
    // 取消上传
    cancelUpload() {
      this.imageSrc = null;
    },
    // 选择框改变时的方法
    handleChange(file, fileList) {
      console.log('选择框改变时imageSrc=' + this.imageSrc);

      const isImage = file.raw.type.startsWith('image/');
      const isWithinSizeLimit = file.size <= 20 * 1024 * 1024;
      if (!isImage || !isWithinSizeLimit) {
        if (!isImage) {
          this.$message.error('只能上传图片文件！');
        } else {
          this.$message.error('上传图片失败，图片不允许超过20MB！');
        }
        location.reload();
        return;
      }

      const isNotEmpty = file.raw.size > 0; // 检查文件大小是否大于0
      if (!isImage || !isNotEmpty) {
        if (!isImage) {
          this.$message.error('只能上传图片文件！');
        } else if (!isNotEmpty) {
          this.$message.error('上传图片失败，文件不能为空！');
        }
        location.reload();
        return;
      }

      const allowedTypes = ['image/jpeg', 'image/png'];
      const isAllowedImageType = allowedTypes.includes(file.raw.type);
      if (!isAllowedImageType) {
        this.$message.error('上传图片失败，请使用以下类型的图片文件：' + allowedTypes.join(', ') + '！');
        location.reload();
        return;
      }

      const reader = new FileReader();
      reader.onload = (event) => {
        this.imageSrc = event.target.result;
        this.loadImage();
      };
      reader.readAsDataURL(file.raw);
    },
    // 获取图片像素信息
    loadImage() {
      const img = new Image();
      img.onload = () => {
        this.width = img.width;
        this.height = img.height;
      };
      img.src = this.imageSrc;
    },
    // 上传按钮
    submitUpload() {
      this.$refs.upload.submit();
      this.imageSrc = null;
    },
    // 上传成功后的回调
    onSuccess(response) {
      console.log('上传成功，开始上传回调');
      console.log('response=' + JSON.stringify(response));
      let data = {
        albumId: this.album.id,
        imageName: response.data.imageName,
        url: response.data.url,
        type: response.data.contentType,
        width: this.width,
        height: this.height,
        sort: 99
      };

      let url = "http://localhost:9180/pictures/add-new";
      console.log('url = ' + url);

      let formData = this.qs.stringify(data);
      console.log('formData = ' + formData);

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          }).post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '上传成功！',
            type: 'success'
          });
          this.imageSrc = null;
          this.loadImageList();
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              location.reload();
            }
          });
          this.imageSrc = null;
          this.loadImageList();
        }
      })
    },
    // 打开封面设置框
    openSetCoverConfirm(picture) {
      this.$confirm('确定将此图片设置为相册封面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleSetCover(picture);
      }).catch(() => {
      });
    },
    // 设置封面
    handleSetCover(picture) {

      if (picture.isCover == 1) {
        return;
      }

      let url = "http://localhost:9180/pictures/" + picture.id + "/setCover";
      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          }).post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '设置封面成功！',
            type: 'success'
          });
          this.loadImageList();
        } else if (jsonResult.state == 40400) {
          this.$message({
            showClose: true,
            message: jsonResult.message,
            type: 'error'
          });
        } else if (jsonResult.state == 40900) {
          this.$message({
            showClose: true,
            message: jsonResult.message,
            type: 'error'
          });
        } else {
          this.$message({
            showClose: true,
            message: jsonResult.message,
            type: 'error'
          });
        }
      })


    },
    // 删除确认框
    deleteImageConfirm(picture) {
      let message = '您确定删除此图片吗？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDeleteImage(picture);
      }).catch(() => {
      });
    },
    // 删除图片
    handleDeleteImage(picture) {
      let url = "http://localhost:9180/pictures/" + picture.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          }).post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            showClose: true,
            message: '删除图片成功！',
            type: 'success'
          });
          this.loadImageList();
        } else {
          this.$message({
            showClose: true,
            message: jsonResult.message,
            type: 'error'
          });
        }
      })
    },
    // 加载相册信息
    loadAlbumInfo() {
      let albumId = parseInt(this.$router.currentRoute.query.albumId);
      console.log('albumId=' + albumId);
      if (!albumId || albumId < 1) {
        let message = '参数错误，无法加载相册数据！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/sys-admin/product/album');
          }
        });
      }

      let url = 'http://localhost:9180/albums/' + albumId;
      console.log('url=' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.album = jsonResult.data;
          this.loadImageList();
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/album');
            }
          });
        }
      })
    },
    // 加载相册图片列表
    loadImageList() {
      let url = 'http://localhost:9180/albums/list/' + this.album.id;
      console.log('url=' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}}).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.pictureList = jsonResult.data.list;
          console.log('picList='+JSON.stringify(this.pictureList));
          this.srcList = this.pictureList.map(item => item.url);
          console.log('list=' + JSON.stringify(this.srcList));
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/album');
            }
          });
        }
      })

    }
  },
  mounted() {
    this.loadAlbumInfo();
  }
}
</script>
<style>
.picture-list .upload {
  margin-bottom: 20px;
  padding: 10px;
  height: 50px;
  display: flex;
  align-items: center; /* 垂直居中 */
}

.upload-main {
  width: 30%;
  margin-right: 20px;
  float: left;
  display: inline;
}

.tips {
  background: #fcf6f6;
  border: 1px solid #aaa;
  margin-right: 20px;
  padding: 10px 20px;
  font-size: 12px;
  float: left;
  width: 40%;
  display: inline;
}

.tips i {
  color: #F56C6C;;
  font-style: normal;
}

.tips p {
  display: inline;
}

.picture-list .picture-item {
  width: 230px;
  height: 230px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 1px solid #e8e6e6;
  border-radius: 6px;
  float: left;
  display: inline;
  position: relative;
}

.picture-list .picture-item .image {
  width: 230px;
  height: 230px;
  border-radius: 6px;
}

.picture-list .picture-item .cover-flag {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  border-top-left-radius: 6px;
}

.picture-list .picture-item .cover-flag .cover-button {
  background: transparent;
  border: none;
  border-top-left-radius: 6px;
  font-size: 20px;
  padding: 8px;
}

.picture-list .picture-item .cover-flag .cover-button:hover {
  background: #fcefef;
}

.picture-list .picture-item .cover-flag .cover {
  color: #f00;
}

.picture-list .picture-item .cover-flag .not-cover {
  color: #aaa;
}

.picture-list .picture-item .delete-button {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 1;
  border-bottom-right-radius: 6px;
}

.picture-list .picture-item .delete-button .button {
  background: transparent;
  border: none;
  border-top-left-radius: 6px;
  font-size: 20px;
  padding: 8px;
}

.picture-list .picture-item .delete-button .button:hover {
  background: #fcefef;
  color: red;
}
</style>